<template>
  <!-- 新增部门的表单 -->
  <div>
    <el-form ref="deptForm" :rules="rules" :model="deptForm" label-width="100px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="deptForm.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="deptForm.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="deptForm.manager" placeholder="请选择部门负责人">
          <el-option
            v-for="item in employess"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="deptForm.introduce" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="hSubmit">{{ isEdit ? '立即修改' : '立即创建' }}</el-button>
        <el-button @click="$emit('close')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeesSimple, addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
export default {
  name: 'DeptDialog',
  props: {
    pid: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    // 验证用户的编码是否重复  rule: 目前的校验规则  value: 用户最新输入的值  callBack: 回调
    var validCode = (rule, value, callBack) => {
      let existCodeList = this.originList.map(item => item.code)
      if (this.isEdit) {
        // 使用 filter 方法筛选出 id 不一致的那一项，这时候只剩余 15 项
        // 将筛选出来 15 项中的 code 取出来形成一个新的数组
        existCodeList = this.originList.filter(item => item.id !== this.pid).map(item => item.code)
      }
      existCodeList.includes(value) ? callBack(new Error(`部门编码${value}已经存在`)) : callBack()
    }
    // 验证同级不能出现重复名称的规则
    var validName = (rule, value, callBack) => {
      let existNameList = this.originList.filter(item => item.pid === this.pid).map(item => item.name)
      // existNameList.includes(value) ? callBack(new Error(`部门名称 ${value} 已经存在`)) : callBack()

      if (this.isEdit) {
        // 获取当前编辑的对象
        const dept = this.originList.find(item => item.id === this.pid)
        const pid = dept.pid
        // 获取当前对象的兄弟, 查找 pid 一样的
        existNameList = this.originList
          .filter(item => item.pid === pid && item.id !== this.pid)
          .map(item => item.name)
      }
      // 2. 使用 includes 方法检测是否存在同名的 name
      existNameList.includes(value) ? callBack(new Error(`部门名称${value}已存在`)) : callBack()
    }
    return {
      deptForm: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      employess: [], // 负责人列表
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择部门管理者', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 300, message: '长度在 1 到 300 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 调用获取负责人列表数据的方法 (下拉选择框使用)
    this.getEmployeesSimple()
    // 调用获取部门详情的方法
    this.getDepartDetail()
  },
  methods: {
    // 获取负责人列表
    async getEmployeesSimple() {
      const res = await getEmployeesSimple()
      this.employess = res.data
    },

    // 获取部门详情
    async getDepartDetail() {
      if (this.isEdit) {
        const res = await getDepartDetail(this.pid)
        this.deptForm = res.data
      }
    },

    // 新增部门的方法
    async addDeptHandler() {
      // 调用 API
      const res = await addDepartments({ ...this.deptForm, pid: this.pid })
      // 给用户提示
      this.$message.success(res.message)
      // 通知父组件更新, 关闭弹框
      this.$emit('update-depart')
    },

    // 编辑部门的方法
    async editDeptHandler() {
      const res = await updateDepartments(this.deptForm)
      // 给用户提示
      this.$message.success(res.message)
      // 通知父组件更新, 关闭弹框
      this.$emit('update-depart')
    },

    // 新增/编辑部门
    async hSubmit() {
      // 兜底验证
      this.$refs.deptForm.validate((valid) => {
        if (valid) {
          this.isEdit ? this.editDeptHandler() : this.addDeptHandler()
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-form-item{
  width:85%
}
.el-select {
  width: 100%;
}
</style>
